﻿using Abp.AspNetCore.Mvc.Controllers;
using Abp.Dependency;
using Abp.Json;
using Alipay.AopSdk.Core.Util;
using Magicodes.Admin.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Magicodes.Alipay
{
    /// <summary>
    /// 支付宝支付回调控制器
    /// </summary>
    [AllowAnonymous]
    [Route("AlipayNotify")]
    public class AlipayNotifyController : AbpController
    {
        public IIocResolver IocResolver { get; set; }

        private readonly IConfigurationRoot configuration;
        private readonly AlipaySettings alipaySettings;

        public AlipayNotifyController(IAppConfigurationAccessor appConfigurationAccessor)
        {
            configuration = appConfigurationAccessor.Configuration;
            alipaySettings = ConfigHelper.GetAlipaySettings(configuration);
        }

        /// <summary>
        /// 根据key存储的支付函数
        /// </summary>
        public static Dictionary<string, Action<Dictionary<string, string>, IIocResolver, bool>> PayActions =
            new Dictionary<string, Action<Dictionary<string, string>, IIocResolver, bool>>();

        /// <summary>
        /// 默认支付函数
        /// </summary>
        public static Action<string, Dictionary<string, string>, IIocResolver, bool> DefaultPayAction { get; set; }

        /// <summary>
        /// 支付回调
        /// </summary>
        /// <param name="tenantId"></param>
        /// <returns></returns>
        [HttpPost("{tenantId}")]
        public ActionResult PayNotify(int? tenantId)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            ICollection<string> requestItem = Request.Form.Keys as ICollection<string>;
            foreach (var item in requestItem)
            {
                result.Add(item, Request.Form[item]);
            }
            Logger.Debug("正在处理支付宝支付信息");

            if (result.Count != 0)
            {
                var resultLog = result.ToJsonString();
                Logger.Info(resultLog);
                bool flag = AlipaySignature.RSACheckV1(result, alipaySettings.AlipayPublicKey, alipaySettings.CharSet, alipaySettings.SignType, false);
                if (flag)
                {
                    //获取支付宝支付自定义数据
                    string key;
                    if (!result.ContainsKey("promo_params"))
                    {
                        throw new Abp.UI.UserFriendlyException("自定义参数不允许为空！");
                    }
                    var promoParams = result["promo_params"];
                    if (string.IsNullOrWhiteSpace(promoParams))
                    {
                        throw new Abp.UI.UserFriendlyException("自定义参数不允许为空！");
                    }
                    //获取Key
                    if (promoParams.StartsWith("{"))
                    {
                        var data = JsonConvert.DeserializeObject<JObject>(promoParams);
                        key = data["key"].ToString();
                    }
                    else
                    {
                        key = promoParams;
                    }
                    if (PayActions.ContainsKey(key))
                    {
                        Logger.Info("支付宝支付处理成功，正在回调key: " + key);
                        PayActions[key].Invoke(result, IocResolver, true);
                    }
                    else
                    {
                        if (DefaultPayAction == null)
                            Logger.Error("支付宝支付处理成功，没有找到回调key: " + key);
                        DefaultPayAction?.Invoke(key, result, IocResolver, true);
                    }
                }
                else
                {
                    throw new Abp.UI.UserFriendlyException("签名错误！");
                }
            }

            return Content("success");
        }
    }
}
